package com.lhz.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @Author: LiHuaZhi
 * @Date: 2020/12/27 14:35
 * @Description:
 **/
@Configuration
public class TaskRedisLuaConfig {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @return result 返回 1表示，正常，0表示限制访问
     */
    public boolean runLuaScript(String lockKey, String value) {
        List<String> keyList = Collections.singletonList(lockKey);

        // 执行脚本 删除锁
        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/redisLock.lua")));
        redisScript.setResultType(String.class);
        String execute = stringRedisTemplate.execute(redisScript, keyList, value);
        // 1-解锁成功，0-失败
        return "1".equals(execute);
    }
}

